package com.example.server;

import com.example.client.ClientData;
import com.example.util.iotDao;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.*;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import static com.example.server.ServerLog.clientDataList;

public class ServerLogController {
    @FXML
    private ComboBox<String> addressComboBox;
    public static int type = 0;

    @FXML
    private TableView<ClientData> serverLogTable;
    @FXML
    private TableColumn<ClientData, String> dateColumn;
    @FXML
    private TableColumn<ClientData,String> timeColumn;

    @FXML
    private Label temperatureLabel;
    @FXML
    private Label humidityLabel;
    @FXML
    private Label co2Label;
    @FXML
    private Label luxLabel;
    @FXML
    private TextField searchTextField;
    @FXML
    public LineChart<String,Number> lineChart;
    @FXML
    public LineChart<String,Number> lineChart1;
    @FXML
    public LineChart<String,Number> lineChart2;
    @FXML
    public LineChart<String,Number> lineChart3;


    ServerLog serverLog;
    iotDao iD = new iotDao();

    //默认构造函数
    public ServerLogController(){//！！public 修饰，否则只能包内访问，无法加载fxml文件。实在是太笨的错误了，改了一晚上，谢谢孙剑桥老师哈哈哈
    }


    public void setServerLog(ServerLog serverLog){
        this.serverLog = serverLog;
        serverLogTable.setItems(serverLog.getData());
    }


    public void showDataDetails(ClientData clientData){
        System.out.println("showDataDetails");
        if(clientData!=null){
            System.out.println("该条数据不为空，采集日期为：" + clientData.getDate());
            //补充表格右边的详细信息
            temperatureLabel.setText(clientData.getTemperature());
            humidityLabel.setText(clientData.getHumidity());
            co2Label.setText(clientData.getCo2());
            luxLabel.setText(clientData.getLux());
        }else{
            System.out.println("该条数据为空");
            temperatureLabel.setText("0");
            humidityLabel.setText("0");
            co2Label.setText("0");
            luxLabel.setText("0");
        }
    }

    @FXML
    public void initialize(){
        //初始化表格
        System.out.println("initialize");
        ////我们在表格列上使用setCellValueFactory(...) 来确定为特定列使用ClientData对象的某个属性
        dateColumn.setCellValueFactory(cellData -> cellData.getValue().dateProperty());
        timeColumn.setCellValueFactory(cellData -> cellData.getValue().timeProperty());

        //数据初始化为空字符串
        showDataDetails(null);
        //为table绑定事件监听，点击条目后修改当前的显示数据
        serverLogTable.getSelectionModel().selectedItemProperty().addListener(
                (observable, oldValue, newValue) -> showDataDetails(newValue)
        );

        //设置下拉列表选项
        ObservableList<String> observableList = FXCollections.observableArrayList("所有数据","长沙市天心区", "长沙市芙蓉区", "长沙市开福区","长沙市雨花区");
        addressComboBox.setItems(observableList);
        addressComboBox.getSelectionModel().selectedItemProperty().addListener((options,oldValue,newValue) -> {

            //初始化表格
            lineChart.getData().clear();
            lineChart1.getData().clear();
            lineChart2.getData().clear();
            lineChart3.getData().clear();

            System.out.println(newValue);
            try {
                //更新serverLog中的数据内容
                serverLog.showList(newValue);
                //将数据显示在左边的表格中
                serverLogTable.setItems(serverLog.getData());
                //向表格中传数据

                CategoryAxis xAxis = new CategoryAxis();
                NumberAxis yAxis = new NumberAxis();

                //Setting label to the axis
                xAxis.setLabel("时间");
                yAxis.setLabel("温度");
                XYChart.Series<String, Number> series = new XYChart.Series<String, Number>();
                series.setName("温度变化");

                XYChart.Series<String, Number> series1 = new XYChart.Series<String, Number>();
                series1.setName("湿度变化");

                XYChart.Series<String, Number> series2 = new XYChart.Series<String, Number>();
                series2.setName("co2变化");

                XYChart.Series<String, Number> series3 = new XYChart.Series<String, Number>();
                series3.setName("光强变化");

                //写入数据
                ClientData clientData;
                for(int i=serverLog.clientDataList.size()-9; i<serverLog.clientDataList.size(); i++) {
                    clientData= serverLog.clientDataList.get(i);
                    series.getData().add(new XYChart.Data<String, Number>(clientData.getTime(),Double.parseDouble(clientData.getTemperature())));
                    series1.getData().add(new XYChart.Data<String, Number>(clientData.getTime(),Double.parseDouble(clientData.getHumidity())));
                    series2.getData().add(new XYChart.Data<String, Number>(clientData.getTime(),Double.parseDouble(clientData.getCo2())));
                    series3.getData().add(new XYChart.Data<String, Number>(clientData.getTime(),Double.parseDouble(clientData.getLux())));

                }

                lineChart.getData().add(series);
                lineChart1.getData().add(series1);
                lineChart2.getData().add(series2);
                lineChart3.getData().add(series3);


            } catch (IOException | SQLException e) {
                e.printStackTrace();
            }

        });

    }

    public void onSearchButtonClick(ActionEvent actionEvent) throws SQLException {
        System.out.println("点击搜索按钮--------------------------------------------------------------------------------------");
        clientDataList = FXCollections.observableArrayList();
        clientDataList.clear();

        String date = searchTextField.getText();
        String address = addressComboBox.getValue();
        ResultSet rs = iD.searchData(date,address);
        if(rs.getRow() == 0)
            System.out.println("rs == null");


        System.out.println("date:" +date + " address:" + address );

        ResultSetMetaData rsmd = rs.getMetaData();
        while (rs.next()) {
            ClientData clientData = new ClientData();

            for (int j = 1; j <= 7; j++) {
                if (j > 1) System.out.print(",  \n");
                String columnValue = rs.getString(j);
                switch(j%7){
                    case 2:
                        clientData.setDate(columnValue);
                        break;
                    case 3:
                        clientData.setTime(columnValue);
                        break;
                    case 4:
                        clientData.setTemperature(columnValue);
                        break;
                    case 5:
                        clientData.setHumidity(columnValue);
                        break;
                    case 6:
                        clientData.setCo2(columnValue);
                        break;
                    case 0:
                        clientData.setLux(columnValue);
                        clientDataList.add(clientData);
                        break;
                }
                System.out.print(columnValue + " " + rsmd.getColumnName(j));
            }

        }
        serverLogTable.setItems(serverLog.getData());

    }

    public void onErrorButtonClick(ActionEvent actionEvent) throws SQLException {
        System.out.println("点击搜索异常数据按钮--------------------------------------------------------------------------------------");
        clientDataList = FXCollections.observableArrayList();
        clientDataList.clear();

        String address = addressComboBox.getValue();
        System.out.println("address:" + address);
        //iotDao iotDao = new iotDao();
        ResultSet rs = iD.searchData(address);

        rs.last();
        int row = rs.getRow();
        rs.beforeFirst();
        System.out.println("rs row =" + row);

        while (rs.next()) {
            ClientData clientData = new ClientData();
            boolean flag = true;
            for (int j = 1; j <= 7; j++) {
                //if (j > 1) System.out.print(",  \n");
                String columnValue = rs.getString(j);
                switch(j%7){
                    case 2:
                        clientData.setDate(columnValue);
                        break;
                    case 3:
                        clientData.setTime(columnValue);
                        break;
                    case 4:
                        clientData.setTemperature(columnValue);
                        double temperature = Double.parseDouble(columnValue);
                        if(temperature>48||temperature<-18)
                            flag = false;
                        break;
                    case 5:
                        clientData.setHumidity(columnValue);
                        double humidity = Double.parseDouble(columnValue);
                        if(humidity>98||humidity<2)
                            flag = false;
                        break;
                    case 6:
                        clientData.setCo2(columnValue);
                        int co2 = Integer.parseInt(columnValue);
                        if(co2>1998||co2<2)
                            flag = false;
                        break;
                    case 0:
                        clientData.setLux(columnValue);
                        int lux = Integer.parseInt(columnValue);
                        if(lux>498||lux<2)
                            flag = false;
                        if(!flag)
                            clientDataList.add(clientData);
                        break;
                }
            }
        }
        serverLogTable.setItems(serverLog.getData());

    }
}
